package com.atguigu.tingshu.common.minio.config;

import com.atguigu.tingshu.common.minio.service.FileOpsService;
import com.atguigu.tingshu.common.minio.service.impl.FileOpsServiceImpl;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author：yyj
 * @Package：com.atguigu.tingshu.album.config
 * @Project：tingshu_parent240829
 * @name：MinioAutoConfiguration
 * @Date：2025/1/14 19:40
 * @Filename：MinioAutoConfiguration
 */

@Configuration
@EnableConfigurationProperties(MinioProperties.class)
@ConditionalOnProperty(prefix = "minio",value ="enable",havingValue = "true")
public class MinioAutoConfiguration {
    Logger logger = LoggerFactory.getLogger(MinioAutoConfiguration.class);

    @Bean
    public MinioClient minioClient(MinioProperties minioProperties) {

        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(minioProperties.getEndpointUrl())  // minio服务器的地址在哪里
                        .credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
                        .build();


        boolean found = false;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());

            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket demo already exists.");
            }
            return minioClient;
        } catch (Exception e) {
            logger.error("初始化失败:"+e.getMessage());
            throw new RuntimeException(e);
        }
    }

    @Bean
    public FileOpsService fileOpsService(){
        return new FileOpsServiceImpl();
    }
}
